package org.bjf.modules.sys.web.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.bjf.modules.core.web.core.PageVO;
import org.bjf.modules.core.web.core.ThreadContext;
import org.bjf.modules.sys.bean.SysRolePerm;
import org.bjf.modules.sys.bean.SysUser;
import org.bjf.modules.sys.annotation.AuthModule;
import org.bjf.modules.sys.query.SysUserQuery;
import org.bjf.modules.sys.service.SysRolePermService;
import org.bjf.modules.sys.service.SysUserRoleService;
import org.bjf.modules.sys.service.SysUserService;
import org.bjf.security.PasswordUtil;
import org.bjf.security.satoken.SaTokenAdminUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 后台用户管理
 *
 * @author icemo
 */
@RestController
@RequestMapping("admin")
@AuthModule(code = "sysuser", desc = "后台用户管理 ")
public class SysUserController {

    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysUserRoleService userRoleService;
    @Autowired
    private SysRolePermService rolePermService;

    @RequestMapping("sys-user/detail")
    public SysUser detail(@RequestParam long id) {
        return sysUserService.get(id);
    }

    @RequestMapping("sys-user/list")
    @SaCheckPermission(value = "admin.list", type = SaTokenAdminUtil.TYPE)
    public List<SysUser> list(SysUserQuery query) {
        return sysUserService.list(query);
    }

    @RequestMapping("sys-user/listPage")
    public PageVO<SysUser> listPage(SysUserQuery query) {
        return sysUserService.listPage(query);
    }

    @RequestMapping("sys-user/listAll")
    public List<SysUser> listAll(SysUserQuery query) {
        return sysUserService.listAll(query);
    }


    @RequestMapping("sys-user/add")
    @SaCheckPermission(value = "sysuser-add", orRole = "super-admin", type = SaTokenAdminUtil.TYPE)
    public void add(@Validated SysUser user) {
        user.setPassword(PasswordUtil.encode(user.getPassword()));
        sysUserService.add(user);
    }

    @RequestMapping("sys-user/update")
    @SaCheckPermission(value = "sysuser-update", orRole = "super-admin", type = SaTokenAdminUtil.TYPE)
    public void update(@Validated SysUser user) {
        if (StringUtils.isNotBlank(user.getPassword())) {
            user.setPassword(PasswordUtil.encode(user.getPassword()));
        }
        sysUserService.updateById(user);
    }

    @RequestMapping("sys-user/delete")
    @SaCheckPermission(value = "sysuser-delete", orRole = "super-admin", type = SaTokenAdminUtil.TYPE)
    public void delete(@RequestParam long id) {
        sysUserService.deleteById(id);
    }


    /**
     * 更新用户角色（分配角色）
     */
    @RequestMapping("sys-user/update-role")
    @SaCheckPermission(value = "sysuser-update", orRole = "super-admin", type = SaTokenAdminUtil.TYPE)
    public void updateRole(@RequestParam Long userId, @RequestParam String roleIds) {
        userRoleService.updateRole(userId, roleIds);
    }

    /**
     * 查询登录用户的权限列表
     */
    @RequestMapping("sys-user/listPerm")
    public List<String> listPerm() {
        long userId = ThreadContext.getLoginInfo().getUserId();
        List<SysRolePerm> userPerms = rolePermService.listUserPerm(userId);
        Map<String, List<SysRolePerm>> moduleGroup = userPerms.stream().collect(Collectors.groupingBy(SysRolePerm::getAuthModuleCode));
        List<String> perms = Lists.newArrayList();
        moduleGroup.forEach((moduleCode, list) -> {
            for (SysRolePerm rolePerm : list) {
                perms.add(rolePerm.getAuthModuleCode() + "-" + rolePerm.getPermMethodCode());
            }
        });

        return perms;
    }
}
